package com.msb.apipassenger.interceptor;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.msb.internalcommon.constant.TokenTypeConstants;
import com.msb.internalcommon.dto.ResponseResult;
import com.msb.internalcommon.dto.TokenResult;
import com.msb.internalcommon.util.JWTUtils;
import com.msb.internalcommon.util.RedisPrefixUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.SignatureException;

/**
 * @Auther: WuWen
 * @Date: 2023/8/16 - 08 - 16 - 15:21
 * @Description: com.msb.apipassenger.interceptor
 * @version: 1.0
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean result = true;
        String resultString = "";

        String token = request.getHeader("authorization");

        TokenResult tokenResult = JWTUtils.checkToken(token);


        if (tokenResult == null) {
            resultString = "token invalid";
            result = false;
        } else {

            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();
            String tokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenTypeConstants.ACCESS_TOKEN);

            // 从redis中读取token
            String redisToken = stringRedisTemplate.opsForValue().get(tokenKey);

            // 比较token是否相等 或者redis中是否有对应的值
            if ((!redisToken.trim().equals(token.trim())) || StringUtils.isBlank(redisToken)) {
                resultString = "token invalid";
                result = false;
            }

        }

        if (!result) {
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.toJSON(ResponseResult.fail(resultString)).toString());
        }


        return result;
    }
}
